package com.ping.study.utils;

import com.ping.study.mapper.UrlsMapper;
import com.ping.study.model.dto.NbaStatsRequestDto;
import com.ping.study.model.vo.ApiResponse;
import com.ping.study.model.vo.Game;
import com.ping.study.model.vo.Group;
import com.ping.study.pojo.Games;
import com.ping.study.pojo.Urls;
import com.ping.study.service.GamesService;
import com.ping.study.service.tx.MatchService;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.client.WebClient;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Data
@Slf4j
public class NbaApi {

    @Autowired
    private GamesService gamesService;

    private WebClient webClient;

    @Autowired
    private MatchService matchService;

    @Autowired
    private UrlsMapper urlsMapper;

    public NbaApi(@Qualifier("nbaWebClient")WebClient webClient) {
        this.webClient = webClient;
    }

    public List<Games> addGames() {
        // 创建请求DTO（会自动设置当前时间戳和日期）
        NbaStatsRequestDto requestParams = new NbaStatsRequestDto();
        log.info("{}", requestParams);
        log.info("进入{},执行{}", this.getClass().getName(), "getGames");
        //获取所有当天直播id
        List<String> lives = matchService.getPlayoffLiveIdsBlocking(LocalDate.now(), LocalDate.now());
        List<Games> gameEntities = webClient.get()
                .uri("/game/schedule", uriBuilder -> uriBuilder
                        .queryParam("app_key", requestParams.getAppKey())
                        .queryParam("app_version", requestParams.getAppVersion())
                        .queryParam("channel", requestParams.getChannel())
                        .queryParam("device_id", requestParams.getDeviceId())
                        .queryParam("install_id", requestParams.getInstallId())
                        .queryParam("network", requestParams.getNetwork())
                        .queryParam("os_type", requestParams.getOsType())
                        .queryParam("os_version", requestParams.getOsVersion())
                        .queryParam("sign", requestParams.getSign())
                        .queryParam("sign2", requestParams.getSign2())
                        .queryParam("t", requestParams.getT())
                        .queryParam("start", requestParams.getStart())
                        .queryParam("end", requestParams.getEnd())
                        .build())
                .retrieve()
                .bodyToMono(ApiResponse.class)
                .map(response -> {
                    log.info("{}", response);
                    List<Games> entities = new ArrayList<>();
                    // 遍历groups中的games
                    for (Group group : response.getData().getGroups()) {
                        for (int i = 0; i < group.getGames().size(); i++){
                            Games entity = new Games();
                            entity.setDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                            entity.setGameId(group.getGames().get(i).getGameId());
                            entity.setHomeTeamName(group.getGames().get(i).getHomeTeamName());
                            entity.setAwayTeamName(group.getGames().get(i).getAwayTeamName());
                            entity.setHomeTeamLogoDark(group.getGames().get(i).getHomeTeamLogoDark());
                            entity.setAwayTeamLogoDark(group.getGames().get(i).getAwayTeamLogoDark());
                            entity.setPlayId(lives.get(i));
                            // 合并日期和时间
                            String dateTimeStr = group.getGames().get(i).getStartDate() + " " + group.getGames().get(i).getStartTime();
                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                            try {
                                entity.setStartTime(format.parse(dateTimeStr));
                            } catch (ParseException e) {
                                // 处理异常或设置默认值
                                entity.setStartTime(null);
                            }
                            for (int j = 0; j < 2; j++){
                                Urls urls = new Urls(); // 每次新建一个对象
                                urls.setGameId(entity.getGameId());
                                switch (j) {
                                    case 0:
                                        urls.setType("tx");
                                        urls.setUrl("");
                                        break;
                                    case 1:
                                        urls.setType("zb");
                                        urls.setUrl("");
                                        break;
                                }
                                urlsMapper.insertSelective(urls);
                            }
                            gamesService.insertGames(entity);
                            entities.add(entity);
                        }
//                        for (Game game : group.getGames()) {
//                            Games entity = new Games();
//                            entity.setDate(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
//                            entity.setGameId(game.getGameId());
//                            entity.setHomeTeamName(game.getHomeTeamName());
//                            entity.setAwayTeamName(game.getAwayTeamName());
//                            entity.setHomeTeamLogoDark(game.getHomeTeamLogoDark());
//                            entity.setAwayTeamLogoDark(game.getAwayTeamLogoDark());
//
//                            // 合并日期和时间
//                            String dateTimeStr = game.getStartDate() + " " + game.getStartTime();
//                            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//                            try {
//                                entity.setStartTime(format.parse(dateTimeStr));
//                            } catch (ParseException e) {
//                                // 处理异常或设置默认值
//                                entity.setStartTime(null);
//                            }
//                            gamesService.insertGames(entity);
//                            entities.add(entity);
//                        }
                    }
                    return entities;
                })
                .block();
        return gameEntities;
    }
}
